//
//  HJHomeViewController.swift
//  Micro-blog Sina
//
//  Created by admin on 16/3/20.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit
import SVPullToRefresh

private let ReuseIdentifier = "ReuseIdentifier"
class HJHomeViewController: HJBaseTableViewController {
    // Blog data
    var statuses: [HJStatuses]? {
        didSet {
            self.tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if !HJUserAccountViewModel.sharedInstance.userLogin {
            return
        }
        setupNavigationBar()
        prepareTableView()
    }
    
    func prepareTableView() {
        tableView.registerClass(HJStatusViewCell.self, forCellReuseIdentifier: ReuseIdentifier)
        
//        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        // 下拉刷新
        tableView.addPullDownRefreshHandler { [weak self] () -> () in
            self?.loadNewStatus()
        }
        tableView.startRefreshing()
    }
    
    private func loadNewStatus() {
        let since_id = self.statuses?.first?.id ?? 0
        HJStatusViewModel.sharedInstance.loadStatus(since_id, max_id: 0) { [weak self] (statuses, error) -> () in
            self?.tableView.stopRefreshing()
            if error != nil {
                HJPrint(msg: "下拉加载微博数据出错 error = \(error)")
                return
            }
            
            let count = statuses?.count ?? 0
            if since_id > 0 {
                self?.showTipLabel(count)
            }
            
            if count == 0 {
                HJPrint(msg: "没有加载到微博数据")
                return
            }
            // 首次加载，since_id默认是0
            if since_id > 0 {
                HJPrint(msg: "下拉刷新count \(count)")
                // 下拉刷新需要将新有的数据拼接到现有数据的前面
                self?.statuses = statuses! + self!.statuses!
            }else {
                HJPrint(msg: "首次加载最新微博count \(count)")
                self?.statuses = statuses
                // 上拉加载更多
                self?.tableView.addInfiniteScrollingWithActionHandler { () -> Void in
                    self?.loadMoreStatus()
                }
            }
            HJPrint(msg: "最终微博数据条数 \(self?.statuses?.count)")
        }
    }
    
    private func loadMoreStatus() {
        let max_id = self.statuses?.last?.id ?? 0
        HJStatusViewModel.sharedInstance.loadStatus(0, max_id: max_id) { (statuses, error) -> () in
            self.tableView.infiniteScrollingView.stopAnimating()
            if error != nil {
                HJPrint(msg: "上拉加载微博数据出错 error = \(error)")
                return
            }
            let count = statuses?.count ?? 0
            if count == 0 {
                HJPrint(msg: "没有加载到微博数据")
                return
            }
            self.statuses = self.statuses! + statuses!
            HJPrint(msg: "上拉加载更多数据 \(statuses?.count)")
            HJPrint(msg: "最终微博数据条数 \(self.statuses?.count)")
            
        }
    }
    
    private func showTipLabel(count: Int) {
        tipLabel.text = count == 0 ? "没有新的微博数据" : "更新了\(count)条微博数据"
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        // Animation
        UIView.animateWithDuration(HJDefaultDuration * 4, animations: { () -> Void in
            self.tipLabel.frame.origin.y = 44
            }) { (_) -> Void in
                UIView.animateWithDuration(HJDefaultDuration * 4, delay: HJDefaultDuration * 2, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    self.tipLabel.frame.origin.y = -64
                    }, completion: nil)
        }
    }
    
    private func setupNavigationBar() {
        setBarButtonItem()
        setupTitleButton()
    }
    
    private func setBarButtonItem() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: "didClickLeftItemEvent")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "didClickRightItemEvent")
    }
    private func setupTitleButton() {
        let name = HJUserAccountViewModel.sharedInstance.userAccount?.screen_name
        let titleButton = HJHomeTitleButton(title: name, imageName: "navigationbar_arrow_down")
        titleButton.addTarget(self, action: "didClickTitleButton:", forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleButton
    }
    
    // MARK: - Button click event
    func didClickLeftItemEvent() {
        HJPrint(msg: "didClickLeftItemEvent")
    }
    func didClickRightItemEvent() {
        HJPrint(msg: "didClickRightItemEvent")
    }
    // MARK: - TitleButton click event
    @objc private func didClickTitleButton(button: HJHomeTitleButton) {
        button.selected = !button.selected
        UIView.animateWithDuration(HJDefaultDuration) { () -> Void in
            button.imageView?.transform = button.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.001)) : CGAffineTransformIdentity
        }
        if button.selected {
            // iOS8.0 later
            let popoverVC = HJPopoverViewController()
            popoverVC.modalPresentationStyle = UIModalPresentationStyle.Popover
            popoverVC.popoverPresentationController?.delegate = self
            // Popover the arrow points to titeView, the default point to the upper left corner
            popoverVC.popoverPresentationController?.sourceView = navigationItem.titleView
            popoverVC.popoverPresentationController?.sourceRect = navigationItem.titleView!.bounds
            popoverVC.preferredContentSize = CGSize(width: 200, height: 44 * popoverVC.titles.count)
            presentViewController(popoverVC, animated: true, completion: nil)
        }
    }
    // MARK: - Lazy load
    private lazy var tipLabel: UILabel = {
        let tipLabel = UILabel()
        tipLabel.backgroundColor = UIColor.orangeColor()
        tipLabel.textColor = UIColor.whiteColor()
        tipLabel.font = UIFont.systemFontOfSize(16)
        tipLabel.textAlignment = NSTextAlignment.Center
        tipLabel.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 44)
        self.navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        return tipLabel
    }()
}

// MARK: - TableView data source
extension HJHomeViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! HJStatusViewCell
        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifier) as! HJStatusViewCell
        cell.status = statuses?[indexPath.row]
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = self.statuses![indexPath.row]
        if status.rowHeight != nil {
//            HJPrint(msg: "模型中保存了行高: \(indexPath), \(status.rowHeight!)")
            return status.rowHeight!
        }
//        HJPrint(msg: "没有缓存过行高")
        let cell = tableView.dequeueReusableCellWithIdentifier(ReuseIdentifier) as! HJStatusViewCell
        // 将status赋值给cell,cell会根据status里面的内容和autoLayout,会重新计算布局,cell没有拿去显示,只是用来填充内容计算行高
        cell.status = status
        // 根据autolayout和cell控件的内容.获取cell的高度
        let rowHeight = cell.systemLayoutSizeFittingSize(UILayoutFittingExpandedSize).height
        // 将计算好的行高保存到模型里面
        status.rowHeight = rowHeight
        return rowHeight
    }
    
    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }
}

// MARK: - UIPopoverPresentationController delegate
extension HJHomeViewController: UIPopoverPresentationControllerDelegate {
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    
    func popoverPresentationControllerShouldDismissPopover(popoverPresentationController: UIPopoverPresentationController) -> Bool {
        let titleButton = navigationItem.titleView as! HJHomeTitleButton
        didClickTitleButton(titleButton)
        return true
    }
}
